
package guoan.service;

import guoan.core.common.WebConfig;
import guoan.core.dto.DataGridModel;
import guoan.core.dto.PageResponse;
import guoan.domain.Adv;
import guoan.domain.AdvType;
import guoan.domain.Media;
import guoan.repository.AdvRepository;
import guoan.service.weixin.WeiXinService;

import java.util.List;
import java.util.Map;

import org.jeewx.api.wxbase.wxmedia.model.WxUpload;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;

@Service
@Transactional(readOnly = false)
public class AdvService extends PageSerivce<Adv> {
    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private AdvRepository advRepository;
    @Autowired
    private AdvTypeService advTypeService;
    @Autowired
    private KeywordService keywordService;
    @Autowired
    private MediaService mediaService;
    @Autowired
    private WeiXinService weiXinService;

    public PageResponse<Adv> page(Long type, DataGridModel dataGridModel){
        // TODO Auto-generated method stub
        Map<String, Long> paramMap = ImmutableMap.of("EQ_TYPE", type);
        return super.pageResponse(advRepository, paramMap, dataGridModel);
    }

    public Adv findOne(Long id){
        // TODO Auto-generated method stub
        return advRepository.findOne(id);
    }

    /**
     * 保存信息,没有的话新建
     * 
     * @param adv
     * @param path
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void save(Adv adv, Long advTypeId, String keyName, String path){
        // TODO Auto-generated method stub
        String keyName_info = WebConfig.KEYWORD_KEY_INFO_ADV;

        if (adv.getId() == null) {
            if (advTypeId != null) {
                AdvType advType = advTypeService.findOne(advTypeId);
                adv.setAdvType(advType);
            }
            adv.setCreateTime(new DateTime());
/*            if (adv.getImgUrl() != null) {
                WxUpload wxUpload = weiXinService.uploadMedia(
                        WebConfig.WEIXIN_MEDIA_IMG, path + adv.getImgUrl());
                if (wxUpload != null) {
                    Media media = new Media();
                    media.setFileUrl(adv.getImgUrl());
                    media.setMediaId(wxUpload.getMedia_id());
                    media.setCreateTime(new DateTime(Long.valueOf(wxUpload
                            .getCreated_at() + "000")));
                    media.setType(WebConfig.WEIXIN_MEDIA_IMG);
                    mediaService.add(media);
                    adv.setMedia(media);
                }
            }
*/            adv.setKeyName(keyName.trim());
            advRepository.save(adv);
            keywordService.add(keyName, keyName_info, adv.getId());
        } else {
            Adv oldAdv = advRepository.findOne(adv.getId());
            if (advTypeId != null) {
                AdvType advType = advTypeService.findOne(advTypeId);
                oldAdv.setAdvType(advType);
            }
            oldAdv.setImgShow(adv.getImgShow());
            oldAdv.setInfo(adv.getInfo());
            oldAdv.setOrderId(adv.getOrderId());
            oldAdv.setTitle(adv.getTitle());
            oldAdv.setwUrl(adv.getwUrl());
            oldAdv.setContent(adv.getContent());
            oldAdv.setImgUrl(adv.getImgUrl());

            /*if (adv.getImgUrl() != null) {
                if (!adv.getImgUrl().equals(oldAdv.getImgUrl())) {
                    WxUpload wxUpload = weiXinService.uploadMedia(
                            WebConfig.WEIXIN_MEDIA_IMG, path + adv.getImgUrl());
                    if (wxUpload != null) {
                        Media media = new Media();
                        media.setFileUrl(adv.getImgUrl());
                        media.setMediaId(wxUpload.getMedia_id());
                        media.setCreateTime(new DateTime(Long.valueOf(wxUpload
                                .getCreated_at() + "000")));
                        media.setType(WebConfig.WEIXIN_MEDIA_IMG);
                        mediaService.add(media);
                        oldAdv.setMedia(media);
                    }
                    oldAdv.setImgUrl(adv.getImgUrl());
                }
            }*/
            String oldk = oldAdv.getKeyName();
            oldAdv.setKeyName(keyName.trim());
            advRepository.save(oldAdv);
            if (!adv.getType().equals("home")) {
                // 如果更改了关键字则删除老的新建新的
                if (!keyName.equals(oldk)) {
                    keywordService.delete(keyName_info, adv.getId());
                    keywordService.add(keyName, keyName_info, adv.getId());
                }
            }
        }
    }

    public PageResponse<Adv> page(String type, DataGridModel dataGridModel){
        // TODO Auto-generated method stub
        Preconditions.checkNotNull(type, "抱歉，参数错误！");
        Map<String, String> paramMap = ImmutableMap.of("EQ_type", type);
        dataGridModel.setOrder("desc");
        dataGridModel.setSort("orderId");
        return pageResponse(advRepository, paramMap, dataGridModel);
    }

    public void del(Long id){
        // TODO Auto-generated method stub
        advRepository.delete(id);
        keywordService.delete(WebConfig.KEYWORD_KEY_INFO_ADV, id);

    }

    public List<Adv> findTop5ByAdvTypeOrderByOrderIdDesc(Long id){
        // TODO Auto-generated method stub
        return advRepository.findTop5ByAdvTypeIdOrderByOrderIdDesc(id);
    }

    public List<Adv> findByAdvTypeIdOrderByOrderIdDesc(Long id){
        // TODO Auto-generated method stub
        return advRepository.findByAdvTypeIdOrderByOrderIdDesc(id);

    }

    public Adv findHome(){
        // TODO Auto-generated method stub
        Adv adv = advRepository.findTo1ByType("home");
        if (adv == null) {
            adv = new Adv();
            adv.setKeyName("首页 home");
            adv.setType("home");
            advRepository.save(adv);

            String[] kws = adv.getKeyName().trim().split(" ");
            for (String kw : kws) {
                // 更新关键字
                keywordService.add(kw, WebConfig.KEYWORD_KEY_INFO_ADV_HOME,
                        adv.getId());
            }
        }
        return adv;
    }

}
